package com.ck.core.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * <p>Title: ListUtil</p>  
 * <p>Description: listUtil</p>  
 * @author huangf 
 * @date 2018年8月28日
 */
public class ListUtil {
	
	/**
	 *  将一个list均分成n个list,主要通过偏移量来实现的
	 * @param source
	 * @return
	 */
	public static <T> List<List<T>> averageAssign(List<T> source,int n){
		List<List<T>> result=new ArrayList<List<T>>();
		//(先计算出余数)
		int remainder=source.size()%n;
		//然后是商
		int number=source.size()/n;
		//偏移量
		int offset=0;
		for(int i=0;i<n;i++){
			List<T> value;
			if(remainder>0){
				value=source.subList(i*number+offset, (i+1)*number+offset+1);
				remainder--;
				offset++;
			}else{
				value=source.subList(i*number+offset, (i+1)*number+offset);
			}
			result.add(value);
		}
		return result;
	}

	/**
	 * 将一个list 拆分成单个list元素个数为${limit}的n个list
	 * @param source
	 * @param limit
	 * @return
	 */
	public static <T> List<List<T>> singleLimitAssign(List<T> source, int limit) {
		List<List<T>> result = new ArrayList<List<T>>();
		if (source.size() <= limit) {
			result.add(source);
		} else {
			List<T> value;
			// (先计算出余数)
			int remainder = source.size() % limit;
			// 然后是商
			int number = source.size() / limit;
			for (int i = 0; i <= number; i++) {
				if (i < number) {
					value = source.subList(i * limit, (i + 1) * limit);
					result.add(value);
				} else if ( i == number && remainder != 0 ){
					value = source.subList(i * limit, i * limit + remainder);
					result.add(value);
				}
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		int j=30;
		for (int i=1;i<=j;i++) {
			list.add(i+"");
		}
		
		List<List<String>> singleLimitAssign = averageAssign(list, 4);
		System.out.println(singleLimitAssign.size());
		for (List<String> l : singleLimitAssign) {
			System.out.println("====");
			for( String s : l) {
				System.out.println(s);
			}
			System.out.println("====");
		}
	}
}
